package com.fh.controller.financial;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.service.attachment.AttachmentService;
import com.fh.service.building.RecordService;
import com.fh.service.building.bill.BillService;
import com.fh.service.financial.FinancialService;
import com.fh.service.role.ShsRoleService;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.PageData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/**
 * @author :  陈豪
 * @Title: 设置
 * @reason
 * @date 2018/8/6
 */
@Controller
@RequestMapping(value = "/financial")
public class FinancialController extends BaseController {
    @Autowired
    private FinancialService financialService;
    @Autowired
    private BillService billService;
    @Autowired
    private AttachmentService attachmentService;
    @Resource(name = "shsRoleService")
    private ShsRoleService roleService;
    @Resource(name = "recordService")
    private RecordService recordService;
    /**
     * 借款人列表
     */
    @RequestMapping(value = "/BorrowerList", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object BorrowerList(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            //   pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = financialService.BorrowerList(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


    /**
     * 还款人-应收/已收-列表
     */
    @RequestMapping(value = "/receivableList", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object Financialdatalist(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            //   pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = financialService.ReceivabledatalistPage(page);
            //varList = financialService.FinancialdatalistPage(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


    /**
     * 还款人-待放款-列表
     */
    @RequestMapping(value = "/beOverdueList", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object beOverdueList(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            //   pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = financialService.beOverdueListPage(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 还款人-逾期-列表
     */
    @RequestMapping(value = "/pendingMoneyList", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object pendingMoneyList(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            //   pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = financialService.PendingMoneyListPage(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


    /**
     * 业务分析 列表
     */
    @RequestMapping(value = "/ywlistPage", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object ywlistPage(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            //   pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = financialService.ywlistPage(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }


    /**
     * 首页-还款 列表
     */
    @RequestMapping(value = "/hklistPage", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object hklistPage(Page page) {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<PageData> varList;
        String datalayui = null;

        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        try {
            pd = this.getPageData();
            //   pd.put("USER_ID", user.getUSER_ID());
            getPData(page, pd);
            varList = financialService.hklistPage(page);
            datalayui = getLData(page, varList);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return datalayui;
    }

    /**
     * 首页 -- 业务分析
     */
    @RequestMapping(value = "/findYW")
    @ResponseBody
    public PageData findYW(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            PageData data = financialService.findYW(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 首页 -- 还款分析
     */
    @RequestMapping(value = "findHK")
    @ResponseBody
    public PageData findHK(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            PageData data = financialService.findHK(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 费用信息
     */
    @RequestMapping(value = "/showData")
    @ResponseBody
    public PageData showData(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            PageData data = financialService.findShowData(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 费用查看
     */
    @RequestMapping(value = "/findShowPrice")
    @ResponseBody
    public PageData findShowPrice(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            PageData data = financialService.findShowPrice(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }



    /**
     * 借款人信息
     */
    @RequestMapping(value = "/findhkCompany")
    @ResponseBody
    public PageData findhkCompany(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            PageData data = financialService.findBorrower(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }


    /**
     * 借款人信息查看
     */
    @RequestMapping(value = "/findhkPersion")
    @ResponseBody
    public PageData findhkPersion(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            PageData data = financialService.findhkPersion(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 首页--我的消息
     */
    @RequestMapping(value = "/findAllMessage")
    @ResponseBody
    public PageData findAllMessage() {
        PageData pd = this.getPageData();
        PageData res = new PageData();
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        List<PageData> list = new ArrayList<>();
        try {

            pd.put("USER_ID", user.getUSER_ID());
            PageData data = roleService.authListByLoginUser(pd);

            dataAssemble(data, pd);


            list = financialService.findAllMessage(pd);


            res.put("data", list);

            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    //数据组装
    public void dataAssemble(PageData data, PageData pd) {
        String shenhe = "";  //审核
        String hetong = "";  //合同
        String shoufei = "";// 收费
        if(data!=null){
            String auth_code = data.getString("AUTH_CODE");

            //待审批的信息
            //是否有初审
            if (auth_code.indexOf("SHQX_1") > -1) {
                shenhe = "tl.CHECK_STATE = '0'";
            }
            //是否有复审
            if (auth_code.indexOf("SHQX_2") > -1) {
                if (StringUtils.isBlank(shenhe)) {
                    shenhe = "tl.CHECK_STATE = '3'";
                } else {
                    shenhe += " OR tl.CHECK_STATE = '3'";
                }

            }

            //是否有终审
            if (auth_code.indexOf("SHQX_3") > -1) {
                if (StringUtils.isBlank(shenhe)) {
                    shenhe = "tl.CHECK_STATE = '5'";
                } else {
                    shenhe += " OR tl.CHECK_STATE = '5'";
                }

            }

            //是否有合规
            if (auth_code.indexOf("SHQX_4") > -1) {
                if (StringUtils.isBlank(shenhe)) {
                    shenhe = "tl.CHECK_STATE = '7'";
                } else {
                    shenhe += " OR tl.CHECK_STATE = '7'";
                }
            }

            pd.put("shenhe", shenhe);

            //合同到期， 合同将到期
            //是否有合同权限
            if (auth_code.indexOf("HTQX_CK") > -1) {
                hetong = "auth";
            }

            if (auth_code.indexOf("HTQX_ZZ") > -1) {
                hetong = "auth";
            }

            //费用收取提醒信息 逾期
            if (auth_code.indexOf("CWQX_CK") > -1) {
                shoufei = "auth";
            }
            pd.put("hetong", hetong);
            if (auth_code.indexOf("CWQX_FK") > -1) {
                shoufei = "auth";
            }
            if (auth_code.indexOf("CWQX_SF") > -1) {
                shoufei = "auth";
            }
            pd.put("shoufei", shoufei);


        }else{
            shenhe = "tl.CHECK_STATE = '0' OR tl.CHECK_STATE = '3'  OR tl.CHECK_STATE = '5' OR tl.CHECK_STATE = '7'";
            pd.put("shenhe", shenhe);
            hetong = "auth";
            pd.put("hetong", hetong);
            shoufei = "auth";
            pd.put("shoufei", shoufei);
        }



    }


    /**
     * 放款
     */
    @RequestMapping(value = "/saveLoan")
    @ResponseBody
    public PageData saveLoan() {
        PageData pd = this.getPageData();
        PageData res = new PageData();
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {
            String uuid = pd.getString("ID");
            PageData pDsh = new PageData();
            pDsh.put("ID", uuid);
            pDsh.put("STATE", "0");       //状态：0待支付、1已支付
            pDsh.put("BILL_STATE", "1");  //0待放款/1已放款
            billService.shenhebill(pDsh);


            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "放款");//放款
            oppd.put("CONTRACT_ID",uuid);
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);

            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 保存费用
     */
    @RequestMapping(value = "/savePrice")
    @ResponseBody
    public PageData savePrice(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        List<PageData> list = (List<PageData>) JSONArray.toList(JSONArray.fromObject(pd.getString("ATTACHMENT")), PageData.class);
        try {

            String uuid = this.get32UUID();
            PageData pageData = new PageData();
            pageData.put("ID", this.get32UUID());
            pageData.put("CREATE_ID", user.getUSER_ID());
            pageData.put("CREATE_DATE", DateUtil.getTime());
            pageData.put("IS_DEL", 0);
            pageData.put("BILL_ID", pd.getString("BILL_ID"));
            pageData.put("PAY_METHOD", "0");//支付方式：0现金、1银行卡、2支付宝、3微信、4支票等
            pageData.put("COLLECTION_TYPE", "0");//收款类型：0公户、1私户、2第三方代收
            pageData.put("PAY_PRICE", pd.getString("PAY_PRICE"));//支付金额
            pageData.put("PAY_TRANSACTION", pd.getString("PAY_TRANSACTION"));//支付流水号
            pageData.put("IS_RECEIPT", "0");//是否有收据：0没有、1有
            pageData.put("INFO", pd.getString("INFO"));//备注
            pageData.put("PRICE_TYPE", "0");//0收入/1支出
            financialService.savePrice(pageData);
            PageData pDsh = new PageData();
            pDsh.put("ID", pd.getString("BILL_ID"));
            pDsh.put("STATE", "1");       //状态：0待支付、1已支付
            // pDsh.put("BILL_STATE", "1");  //0待放款/1已放款
            pDsh.put("ACT_PAY_DATE", pd.getString("ACT_PAY_DATE"));
            billService.shenhebill(pDsh);


            for (PageData pdAtt : list) {
                PageData pds = new PageData();
                pds.put("ID", this.get32UUID());    //主键
                pds.put("OID", pd.getString("BILL_ID"));
                pds.put("NAME", pdAtt.get("name"));
                pds.put("EXT", pdAtt.get("ext"));
                pds.put("PATH", pdAtt.get("url"));
                pds.put("TYPE", "账单图片");
                pds.put("SORT", "1");
                pds.put("REMARK", "");
                pds.put("CREATE_TIME", new DateUtil().getTime());
                pds.put("CREATE_ID", user.getUSER_ID());
                pds.put("IS_DELETED", 0);
                attachmentService.saveAttachment(pds);

            }


            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID", this.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime()); //创建时间
            oppd.put("DETAILS", "收费");//收费
            oppd.put("CONTRACT_ID",uuid);
            oppd.put("OPERATOR", user.getNAME());
            recordService.save(oppd);
            //修改 账单表
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

    /**
     * 获取借款人list
     */
    @RequestMapping(value = "/BorrowerListPD")
    @ResponseBody
    public PageData BorrowerListPD(Page page) {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            List<PageData> data = financialService.BorrowerListPD(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }
    /**
     * 获取借款人
     */
    @RequestMapping(value = "/findBorrower")
    @ResponseBody
    public PageData findBorrower() {
        PageData pd = this.getPageData();
        PageData res = new PageData();

        try {
            PageData data = financialService.findBorrower(pd);
            res.put("data", data);
            res.put("errcode", "0");
            res.put("errmsg", "ok");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            res.put("data", "");
            res.put("errcode", "1");
            res.put("errmsg", e.toString());
        }
        return res;
    }

}
